from matplotlib import pyplot as plt
from Stu import Student
from Linklei import LinkList
import numpy as np

def jiemian():
    print('*********************************************************************************')
    print('*                             学生成绩管理系统                                    *')
    print('*********************************************************************************')
    print('*                             H = 显示帮助菜单                                    *')
    print('*                             T = 成绩录入                                       *')
    print('*                             A = 计算学生平均分                                  *')
    print('*                             Z = 计算学生总分                                    *')
    print('*                             L = 列出成绩表                                      *')
    print('*                             P = 按平均成绩排序                                   *')
    print('*                             S = 按学号查询学生成绩                               *')
    print('*                             R = 成绩可视化                                      *')
    print('*                             Q = 退出系统                                        *')
    print('*********************************************************************************')
    print('*                           Copyright（c）2025.11.03 By MZQ                      *')
    print('*********************************************************************************')

def Type(linked_list):
    """成绩录入"""
    size1 = int(input("请输入录入学生人数：\n"))
    print(f'请输入{size1}名学生的三门课成绩\n学号 语文 数学 英语')
    for i in range(size1):
        try:
            yuwen, shuxue, yingyu = input(f'{i + 1}\t').split()
            xuehao = i + 1
            linked_list.append(xuehao, yuwen, shuxue, yingyu)
        except ValueError:
            print("输入格式错误，请重新输入")
            break


def List(linked_list):
    """显示成绩表"""
    print(f'学号  语文  数学  英语  平均分 总分')
    # 按学号排序显示
    students = linked_list.xueshengliebiao()
    for student in students:
        print(f'{student.xuehao}    {student.yuwen}    {student.shuxue}    {student.yingyu}    {student.pingjunshu:.2f}    {student.zong:.2f}')


def Average(linked_list):
    """计算平均分"""
    linked_list.calculate_all_averages()
    print('平均分已计算。请使用命令L查看。')


def Sort(linked_list):
    """按平均分排序显示"""
    print(f'请选择排序方式：')
    xuanze=input(f'升序：1\n降序：2\n请输入您的选择：')
    if xuanze == '1':
        sorted_students = linked_list.maopaoshengxu()
        print("按平均分从低到高排序：")
        print(f'学号\t语文\t数学\t英语\t平均分\t总分')
        for student in sorted_students:
            print(f'{student.xuehao}\t{student.yuwen}\t{student.shuxue}\t{student.yingyu}\t{student.pingjunshu:.2f}\t{student.zong:.2f}')
    elif xuanze == '2':
        sorted_students = linked_list.maopaojiangxu()
        print("按平均分从高到低排序：")
        print(f'学号\t语文\t数学\t英语\t平均分\t总分')
        for student in sorted_students:
            print(f'{student.xuehao}\t{student.yuwen}\t{student.shuxue}\t{student.yingyu}\t{student.pingjunshu:.2f}\t{student.zong:.2f}')
    else:
        print('您选择的排序方式不存在！')


def Search(linked_list):
    """学号查询"""
    try:
        xuehao = int(input("请输入要查询的学号："))
        student = linked_list.search(xuehao)
        if student:
            print("找到学生信息：")
            print(f'学号: {student.xuehao}')
            print(f'语文: {student.yuwen}')
            print(f'数学: {student.shuxue}')
            print(f'英语: {student.yingyu}')
            print(f'平均分: {student.pingjunshu:.2f}')
            print(f'总分: {student.zong:.2f}')
        else:
            print(f"未找到学号 {xuehao} 的学生")
    except ValueError:
        print("请输入有效的学号！")


def Zchengji(linked_list):
    linked_list.zongchengji()
    print('总分已计算。请使用命令L查看。')


def Help():
    """显示帮助"""
    jiemian()


def keshi(linked_list):
    """综合可视化分析"""
    # 设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    # 创建一个大画布，包含多个子图
    fig = plt.figure(figsize=(10, 7))
    # 获取数据
    students = linked_list.xueshengliebiao()
    all_scores = linked_list.zongchengji()
    all_students = [f'学号{student.xuehao}' for student in students]
    #  总成绩分布图
    plt.subplot(2, 2, 1)
    plt.title('学生总成绩分布')
    plt.xlabel('学号')
    plt.ylabel('总成绩')
    bars = plt.bar(x=all_students, height=all_scores, alpha=0.8, edgecolor='white', linewidth=1.2, width=0.6)
    for bar, score in zip(bars, all_scores):
        height = bar.get_height()
        plt.text(bar.get_x() + bar.get_width() / 2., height + 1,
                 f'{score:.0f}', ha='center', va='bottom', fontsize=9, fontweight='bold')
    # 平均分排名图
    plt.subplot(2, 2, 2)
    sorted_by_avg = linked_list.maopaojiangxu()
    avg_scores = [student.pingjunshu for student in sorted_by_avg]
    student_names = [f'学号{student.xuehao}' for student in sorted_by_avg]
    plt.title('平均分排名')
    plt.xlabel('平均分')
    plt.ylabel('学生')
    bars = plt.barh(student_names[:10], avg_scores[:10])
    for bar, score in zip(bars, avg_scores[:10]):
        width = bar.get_width()
        plt.text(width + 0.5, bar.get_y() + bar.get_height() / 2,
                 f'{score:.1f}', va='center', ha='left', fontsize=9)
    # 各科目成绩分布直方图
    plt.subplot(2, 2, 3)
    yuwen_scores = [student.yuwen for student in students]
    shuxue_scores = [student.shuxue for student in students]
    yingyu_scores = [student.yingyu for student in students]
    plt.title('各科目成绩分布')
    plt.xlabel('分数段')
    plt.ylabel('人数')
    bins = [0, 60, 70, 80, 90, 100]
    plt.hist([yuwen_scores, shuxue_scores, yingyu_scores], bins=bins,
             label=['语文', '数学', '英语'], alpha=0.7, color=['red', 'blue', 'green'])
    plt.legend()
    plt.tight_layout()
    plt.show()